import React from 'react'
import { Table, Tag, Progress, Card, Row, Col, Statistic } from 'antd'
import { useQuery } from '@tanstack/react-query'
import { api } from '../services/api'
import { 
  CheckCircleOutlined, 
  ClockCircleOutlined, 
  ExclamationCircleOutlined 
} from '@ant-design/icons'

const Pipelines: React.FC = () => {
  const { data: pipelines, isLoading } = useQuery({
    queryKey: ['pipelines'],
    queryFn: api.getPipelines,
  })

  const columns = [
    {
      title: '管道名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          Running: { color: 'green', text: '运行中', icon: <CheckCircleOutlined /> },
          Stopped: { color: 'default', text: '已停止', icon: <ClockCircleOutlined /> },
          Error: { color: 'red', text: '错误', icon: <ExclamationCircleOutlined /> },
          Paused: { color: 'orange', text: '已暂停', icon: <ClockCircleOutlined /> },
        }
        const statusInfo = statusMap[status as keyof typeof statusMap] || statusMap.Stopped
        return (
          <Tag color={statusInfo.color} icon={statusInfo.icon}>
            {statusInfo.text}
          </Tag>
        )
      },
    },
    {
      title: '处理记录数',
      dataIndex: ['metrics', 'records_processed'],
      key: 'records_processed',
      render: (count: number) => count?.toLocaleString() || '0',
    },
    {
      title: '平均延迟',
      dataIndex: ['metrics', 'avg_latency_ms'],
      key: 'avg_latency_ms',
      render: (latency: number) => `${latency?.toFixed(1) || '0'}ms`,
    },
    {
      title: '错误数',
      dataIndex: ['metrics', 'errors_count'],
      key: 'errors_count',
      render: (errors: number) => (
        <Tag color={errors > 0 ? 'red' : 'green'}>
          {errors || 0}
        </Tag>
      ),
    },
    {
      title: '最后同步',
      dataIndex: ['metrics', 'last_sync_at'],
      key: 'last_sync_at',
      render: (date: string) => date ? new Date(date).toLocaleString('zh-CN') : '从未同步',
    },
  ]

  // 计算统计数据
  const stats = pipelines?.reduce((acc: any, pipeline: any) => {
    acc.total += 1
    if (pipeline.status === 'Running') acc.running += 1
    if (pipeline.status === 'Error') acc.error += 1
    acc.totalRecords += pipeline.metrics?.records_processed || 0
    acc.totalBytes += pipeline.metrics?.bytes_processed || 0
    return acc
  }, { total: 0, running: 0, error: 0, totalRecords: 0, totalBytes: 0 }) || {}

  return (
    <div>
      <h1>数据管道</h1>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总管道数"
              value={stats.total}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="运行中"
              value={stats.running}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="错误管道"
              value={stats.error}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="处理记录总数"
              value={stats.totalRecords}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 管道列表 */}
      <Card>
        <Table 
          columns={columns} 
          dataSource={pipelines} 
          loading={isLoading}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 个管道`,
          }}
          expandable={{
            expandedRowRender: (record) => (
              <div style={{ padding: '16px 0' }}>
                <Row gutter={16}>
                  <Col span={8}>
                    <Card size="small" title="数据处理量">
                      <Progress 
                        type="circle" 
                        percent={75} 
                        format={() => `${(record.metrics?.bytes_processed / 1024 / 1024).toFixed(1)}MB`}
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card size="small" title="成功率">
                      <Progress 
                        type="circle" 
                        percent={Math.round((1 - (record.metrics?.errors_count || 0) / (record.metrics?.records_processed || 1)) * 100)}
                        status="active"
                      />
                    </Card>
                  </Col>
                  <Col span={8}>
                    <Card size="small" title="连接数">
                      <div style={{ textAlign: 'center', fontSize: '24px', color: '#1890ff' }}>
                        {record.connections?.length || 0}
                      </div>
                    </Card>
                  </Col>
                </Row>
              </div>
            ),
          }}
        />
      </Card>
    </div>
  )
}

export default Pipelines
